package ru.unlocker.reports.sampler.service;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.cfg.CoercionAction;
import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
import com.fasterxml.jackson.databind.type.LogicalType;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.File;
import java.io.IOException;
import java.util.List;
import lombok.experimental.UtilityClass;
import ru.unlocker.reports.sampler.domain.EventData;

@UtilityClass
public class EventDataReader {

  private static final CsvMapper CSV_MAPPER;

  static {
    CsvMapper mapper = new CsvMapper();
    mapper.coercionConfigFor(LogicalType.Enum).setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsNull);
    mapper.coercionConfigFor(LogicalType.Textual).setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsNull);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.registerModule(new JavaTimeModule());
    CSV_MAPPER = mapper;
  }

  public static List<EventData> readCsv(File csvFile) throws IOException {
    try (
        MappingIterator<EventData> dataIter = CSV_MAPPER
            .readerWithTypedSchemaFor(EventData.class)
            .readValues(csvFile)
    ) {
      return dataIter.readAll();
    }
  }
}
